package ar.com.jwa.controllers;

import java.text.SimpleDateFormat;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import ar.com.jwa.commons.validators.LoginValidator;
import ar.com.jwa.domain.Choices;
import ar.com.jwa.domain.Game;
import ar.com.jwa.domain.User;
import ar.com.jwa.services.SystemFacade;

@Controller
public class UserController {
	
	private Log log = LogFactory.getLog(UserController.class); 
	
	@Autowired
	private SystemFacade systemFacade;
	
	public static final String DATE_FORMAT = "dd-MM HH:mm";

	@SuppressWarnings("finally")
	@RequestMapping("/login.*")
	public ModelAndView login(@ModelAttribute("user") User user,BindingResult bindingResult,HttpServletRequest req, HttpServletResponse res,HttpSession session) {
		
		ModelAndView mav = new ModelAndView();
		
		try{
			
			LoginValidator lv= new LoginValidator(); 
			
			lv.validate(user, bindingResult);
			
			if (bindingResult.hasErrors()) {
				mav.getModel().putAll(bindingResult.getModel());
				mav.setViewName("login");
				return mav;
			}
			
			User loggedPlayer= this.getSystemFacade().login(user);
			
			boolean logged = loggedPlayer != null;			

			if (logged){
				
				req.getSession().setAttribute("User",this.getSystemFacade().getUserByMail(user.getEmail()));
				
				Collection<Game> games = this.getSystemFacade().getGamesToConfirm(loggedPlayer);				

				if ( games.size()!= 0) {
					
					mav.addObject("gameId",games.iterator().next().getId());
					mav.addObject("hasToConfirm",games.size() != 0);
					mav.addObject("date",new SimpleDateFormat(DATE_FORMAT).format(games.iterator().next().getId()));
					mav.addObject("place","Nuñess");
				
				}
				mav.setViewName("home");
				
			}
			else {
				mav.setViewName("login");
				mav.getModel().putAll(bindingResult.getModel());
			}
		
		}catch (Exception e) {
			log.error(e.getMessage());
			mav.setViewName("error");
		}
		
		finally{
			return mav;
		}
	
	}
	
	@RequestMapping("/makeChoice.*")
	public void makeChoice(HttpServletRequest req, HttpServletResponse res,HttpSession session) {
		
		log.info("making a Choice...");
		
		String gameId = req.getParameter("gameId");
		String theChoice = req.getParameter("choice");
		User user = (User) req.getSession().getAttribute("User");
		
		if (theChoice.equals(Choices.ASSIST.toString())){
			this.getSystemFacade().addPlayerToGameConfirmedList(gameId,user.getId());
		}
		
		if (theChoice.equals(Choices.NOT_ASSIST.toString())){
			this.getSystemFacade().addPlayerToGameNotGoingList(gameId,user.getId());
		}
	}
	
	
	@RequestMapping("/setup.*")
	public ModelAndView setupForm(HttpServletRequest req, HttpServletResponse res,HttpSession session){
		ModelAndView mav = new ModelAndView("login");
		return mav;
	}
		
	/**
	 * @return the systemFacade
	 */
	public SystemFacade getSystemFacade() {
		if (this.systemFacade == null)
			throw new RuntimeException("SystemFacade is not setted up");
		return systemFacade;
	}

	/**
	 * @param systemFacade the systemFacade to set
	 */
	public void setSystemFacade(SystemFacade systemFacade) {
		this.systemFacade = systemFacade;
	}

	/**
	 * @return the log
	 */
	public Log getLog() {
		return log;
	}

	/**
	 * @param log the log to set
	 */
	public void setLog(Log log) {
		this.log = log;
	}

}
